import fs = require('fs');
import {Options} from "ejs";
import multer = require('multer');
import express = require('express');
import {Request, Response, NextFunction} from "express";

import PWSApp from "../../core/app";
import {Magics} from "../../core/magics";
import {RouteType} from "../../core/defines";

import {BaseAction} from "../../core/base.action";
import DiskStorage from "../../core/upload.storage";

export default class UploadXls extends BaseAction {
    private _limit: Object;
    private _uploader: any;
    private _options: Options;
    private _storage: DiskStorage;

    constructor(app: PWSApp) {
        super(app);
        this._storage = new DiskStorage(Magics.ExcelPath);
        this._limit = {
            fileSize: Magics.UploadFileMaxSize,
            fieldSize: Magics.UploadFieldMaxSize
        };
        this._options = {};
        this._options['storage'] = this._storage;
        this._options['limits']  = this._limit;
        this._options['fileFilter'] = this._fileFilter;
        this._uploader = multer(this._options);
    }

    name() { return `${this.app.name}UploadXls`; }

    private _fileFilter(req: Request, file: File, cb){
        let type = file['mimetype'];
        let xls = 'application/vnd.ms-excel';
        let xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if( type != xls && type != xlsx){
            let err = new Error("File type is not supported");
            err['code'] = "LIMIT_FILE_TYPE";
            this.logger.D(this.name(), err);
            cb(err);
            return;
        }
        cb(null, true);
    }

    protected _setRoutes() {
        this._route(RouteType.POST, '/admin/prod/upload', this._uploadProd);
        this._route(RouteType.POST, '/admin/prod/upload/std', this._uploadProdStd);
    }

    private _uploadProd(req: Request, res: Response, next: NextFunction) {
        let fields = [{name: "uploadprod", maxCount: 1}];
        let uploader = this._uploader['fields'](fields);
        uploader(req, res, (err) => {
            if (err) {
                this.logger.D(this.name(), err);
                return;
            }
            next();
        });
    }

    private _uploadProdStd(req: Request, res: Response, next: NextFunction){
        let fields = [{name: "uploadprod", maxCount: 1}];
        let uploader = this._uploader['fields'](fields);
        uploader(req, res, (err) => {
            if (err) {
                this.logger.D(this.name(), err);
                return;
            }
            next();
        });
    }
}
